<?php
/*
Plugin Name: SpComm Google Map
Description: Allow [map] shortcode in posts and pages
Plugin URI: https://code.google.com/p/spcomm-gmap/
Author: SAMsan
Author URI: https://plus.google.com/profil/SAMsan
Text Domain: spcomm-gmap
Domain Path: /languages/
Version: 0.1
*/

$SpCommGmap = new SpCommGmap();

class SpCommGmap {

	var $options;
	
	public function SpCommGmap() {
		$this->options = $this->get_options();
		add_shortcode('map', array(&$this,'make_map'));
		add_action ('wp_enqueue_scripts', array(&$this, 'fe_scripts'));
		add_action ( 'admin_menu', array(&$this,'plugin_admin_add_page') );
		add_action ( 'admin_init', array(&$this,'plugin_admin_init') );
		
		add_filter( 'mce_external_plugins', array(&$this,'tinymce_add_buttons') );
		add_filter( 'mce_buttons', array(&$this,'tinymce_register_buttons') );
		
		/* Localize script vars */
		foreach ( array('post.php','post-new.php') as $hook ) {
			add_action( "admin_head-$hook", array(&$this,'tinymce_add_variables') );
		}
	}
	
	function tinymce_add_buttons( $plugin_array ) {
		$plugin_array['SpCommGmap'] = plugins_url( 'js/tinyMCE-plugin.js' , __FILE__ );
		return $plugin_array;
	}
	function tinymce_register_buttons( $buttons ) {
		array_push( $buttons, 'addmap' );
		return $buttons;
	}
	function tinymce_add_variables() {
		?>
		<!-- TinyMCE Shortcode Plugin -->
		<script type='text/javascript'>
		var spcGmapVars = {
			'address':	'<?php echo $this->options['address'] ?>',
			'width':	'<?php echo $this->options['width'] ?>',
			'height':	'<?php echo $this->options['height'] ?>',
			'lat':		false,
			'lng':		false,
			'zoom':		'<?php echo $this->options['zoom'] ?>',
			'image':	'<?php echo $this->options['image'] ?>',
			'link':		'<?php echo '1' ?>',
			'kml':		null
		};
		</script>
		<!-- TinyMCE Shortcode Plugin -->
   		<?php
	}
	
	function get_options() {
		if (! $options = get_option('SpCommGmap_options') ) :
			
			$options = $this->get_default_options();
			
			update_option( 'SpCommGmap_options', $options );
		endif;
		
		return($options);
			
	}
	
	function get_default_options($field=false) {
		
		$options = array (	'gmap_apikey' 	=> __('Enter your API Key'),
							'sensor'		=> 'false',
							'address'		=> '272, route de launaguet 31200 Toulouse, France',
							'width'			=> '100%',
							'height'		=> '300px',
							'zoom' 			=> 13,
							'image'			=> plugins_url( 'images/local-marker.png' , __FILE__ )
						);
		return $field ? $options[$field] : $options;
	}
		
	function plugin_admin_init() {
		
		register_setting (  'SpCommGmap_fields', 			// Options group (used in 'settings_field($options_group)')
							'SpCommGmap_options', 			// Options array name
							array(&$this,'plugin_options_validate')	// Function CB  validate
						 );
		
		add_settings_section (  'SpCommGmap_section', 		// Unique section ID
								__('options générales'), 			// Section title
								array(&$this,'plugin_section_text'), // Function CB for desciption text
								'SpCommGmap_page'			// Page ID (used in 'do_settings_sections($page_id)')
							 );
		
		// FIELDS 
		add_settings_field ( 'SpCommGmap_option_gmap_apikey',
							 __('Clé d\'API Google Maps (v3)'),
							 array(&$this,'plugin_setting_gmap_apikey'),
							 'SpCommGmap_page',
							 'SpCommGmap_section' );
		add_settings_field ( 'SpCommGmap_option_address',
							 __('Adresse'),
							 array(&$this,'plugin_setting_address'),
							 'SpCommGmap_page',
							 'SpCommGmap_section' );
		add_settings_field ( 'SpCommGmap_option_width',
							 __('Largeur'),
							 array(&$this,'plugin_setting_width'),
							 'SpCommGmap_page',
							 'SpCommGmap_section' );
		add_settings_field ( 'SpCommGmap_option_height',
							 __('Hauteur'),
							 array(&$this,'plugin_setting_height'),
							 'SpCommGmap_page',
							 'SpCommGmap_section' );
		add_settings_field ( 'SpCommGmap_option_zoom',
							 __('Niveau de zoom'),
							 array(&$this,'plugin_setting_zoom'),
							 'SpCommGmap_page',
							 'SpCommGmap_section' );
		add_settings_field ( 'SpCommGmap_option_image',
							 __('Image du marqueur'),
							 array(&$this,'plugin_setting_image'),
							 'SpCommGmap_page',
							 'SpCommGmap_section' );
		add_settings_field ( 'SpCommGmap_option_sensor',	// Unique field ID
							 __('Sensor'), 						// Title
							 array(&$this,'plugin_setting_sensor'),// Function CB
							 'SpCommGmap_page',				// Page ID (used in 'do_settings_sections($page_id)')
							 'SpCommGmap_section' );			// Section ID (used in 'add_settings_section($section_id, ...)')
					 
	}
	
	function plugin_admin_add_page() {
		// Add option page under Settings menu
		add_options_page ( 	__('Google Maps'),						// Menu title
							__('Google Maps'),						// Page title
							'manage_options',						// capabilities
							'SpCommGmap',							// unique page ID
							array (&$this,'plugin_options_page')	// function CB
						 );
	}
		
	function plugin_options_page() {
		// Display option page
		?>
        <div class="wrap">
            <h2><?php _e('Autocomplétion des villes') ?></h2>
            <form action="options.php" method="post">
				<?php settings_fields('SpCommGmap_fields'); ?>
                <?php do_settings_sections('SpCommGmap_page'); ?>
                 
                <input name="Submit" type="submit" value="<?php esc_attr_e(__('Enregistrer les options')); ?>" />
            </form>
        </div>
        <?php
	}
	
	//Display settings section
	function plugin_section_text() {
		return null;
	}
	
	// Display settings fields // one CB per field
	function plugin_setting_sensor ()
	{
		$checked = $this->options['sensor'] == 'active' ? "checked='checked'" : null;
		echo "<input type='checkbox' id='SpCommGmap_sensor' name='SpCommGmap_options[sensor]' value='active' $checked />";
	}
	function plugin_setting_gmap_apikey ()
	{
		echo '<input type="text" id="SpCommGmap_gmap_apikey" name="SpCommGmap_options[gmap_apikey]" value="'.$this->options['gmap_apikey'].'" />';
	}
	function plugin_setting_address ()
	{
		echo '<input type="text" id="SpCommGmap_address" name="SpCommGmap_options[address]" value="'.$this->options['address'].'" />';
	}
	function plugin_setting_width ()
	{
		echo '<input type="text" id="SpCommGmap_width" name="SpCommGmap_options[width]" value="'.$this->options['width'].'" />';
	}
	function plugin_setting_height ()
	{
		echo '<input type="text" id="SpCommGmap_height" name="SpCommGmap_options[height]" value="'.$this->options['height'].'" />';
	}
	function plugin_setting_zoom ()
	{
		echo '<input type="text" id="SpCommGmap_zoom" name="SpCommGmap_options[zoom]" value="'.$this->options['zoom'].'" />';
	}
	function plugin_setting_image ()
	{
		echo '<input type="text" id="SpCommGmap_image" name="SpCommGmap_options[image]" value="'.$this->options['image'].'" />';
	}
	
	// Validate options
	function plugin_options_validate( $input )
	{
		// Update options when needed
		$this->options['sensor'] = 		$input['sensor']=='active'	? $input['sensor']		: null;
		$this->options['gmap_apikey'] = $input['gmap_apikey']		? $input['gmap_apikey']	: $this->get_default_options('gmap_apikey');
		$this->options['address'] = 	$input['address'] 			? $input['address']		: $this->get_default_options('address');
		$this->options['width'] = 		$input['width'] 			? $input['width']		: $this->get_default_options('width');
		$this->options['height'] = 		$input['height'] 			? $input['height']		: $this->get_default_options('height');
		$this->options['zoom'] = 		$input['zoom'] 				? $input['zoom']		: $this->get_default_options('zoom');
		$this->options['image'] = 		$input['image'] 			? $input['image']		: $this->get_default_options('image');
		
		return $this->options;
	}
	
	function fe_scripts () {
		$key = $this->options['gmap_apikey'];
		$sensor = $this->options['sensor'];
		wp_enqueue_script('gmap-v3', "//maps.googleapis.com/maps/api/js?key=$key&sensor=$sensor");
	}
	
	function make_map($atts) 
	{
		global $post;
		
		extract( shortcode_atts( array(
			'address'	=> $this->options['address'],
			'width'		=> $this->options['width'],
			'height' 	=> $this->options['height'],
			'lat' 		=> false,
			'lng' 		=> false,
			'zoom'		=> $this->options['zoom'],
			'image' 	=> $this->options['image'],
			'link' 		=> '1'
			/*'kml' 		=> null a implementer */
		), $atts ) );
		
		$size = 'width:'.$width.';height:'.$height.';';
		$map_id = uniqid("map_canvas_");
		$output = '<div id="'.$map_id.'" style="'.$size.'" class="gmap"></div>';
		?>
<script type="text/javascript">
var map;
var myLatlng;
var address 	= "<?php echo $address ?>";
var markerImage	= "<?php echo $image ?>";
var zoom		= <?php echo $zoom ?>;
var mapId		= "<?php echo $map_id ?>";
<?php if ( ($lat && $lng) && ($lat!='false' && $lng!='false') ) : ?>
var lat			= <?php echo $lat ?>;
var lng			= <?php echo $lng ?>;
myLatlng = new google.maps.LatLng(lat, lng);
<?php else : ?>
geocoder = new google.maps.Geocoder();
geocoder.geocode( { "address": address}, function(results, status) {
	if (status == google.maps.GeocoderStatus.OK) {
		myLatlng = new google.maps.LatLng( results[0].geometry.location.k, results[0].geometry.location.B ) ;
	} else {
		alert("Geocode was not successful for the following reason: " + status);
	}
});
<?php endif; ?>
function initialize() {

	var myOptions = {
		zoom: zoom,
		sensor: false,
		center: myLatlng,
		scrollwheel: false
		//mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	//google.maps.visualRefresh = true;
	map = new google.maps.Map(document.getElementById(mapId), myOptions);
	marker = new google.maps.Marker({
		position: myLatlng,
		map: map,
		icon: markerImage
	});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
        <?php
		
		return $output;
	}

}

?>